package hibu.LeiJonGun.activities;

import hibu.LeiJonGun.seniorservice.Control;
import hibu.LeiJonGun.seniorservice.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/* 
 * Written by: Christian L. Gunvaldsen
 * This activity lets the user log in to the application
 */
public class ActLogIn extends Activity {
	
private Control control;
private EditText txtPassword;
private EditText txtUsername;
private ProgressDialog dialog;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_log_in);
        
     	// This "import" the control object so that the activity can use the control to handle database tasks:
        control = ((Control)this.getApplicationContext()); 
		control.setContext(ActLogIn.this);
		control.checkScreenSize();
		
        final int passwordLength = 4;
        final int usernameLength = 4;
        
        final Button btnLogIn = (Button) findViewById(R.id.btnLogIn);
        final Button btnNewUser = (Button) findViewById(R.id.btnNewUser);
    	txtPassword = (EditText) findViewById(R.id.txtPassword);
    	txtUsername = (EditText) findViewById(R.id.txtUsername);
    	
    	Intent intent = getIntent();
    	
    	// If the user has created a new user, or forgot the password, txtUsername and txtPassword will be filled automatically
    	if (intent.getExtras() != null) {
    		if (intent.hasExtra("username")) txtUsername.setText(intent.getExtras().getString("username"));
    		if (intent.hasExtra("password")) txtPassword.setText(intent.getExtras().getString("password"));
    		
    	}
    	
    	// Make button text gray if not enabled
    	if (!btnLogIn.isEnabled()) btnLogIn.setTextColor(ActLogIn.this.getResources().getColor(R.color.lblAssignmentDescriptionDisabled));
    	
    	//Check if log in button should be enabled or not
    	if (txtPassword.length() >= passwordLength && txtUsername.length() >=usernameLength) btnLogIn.setEnabled(true);
    	else btnLogIn.setEnabled(false);
    	
    	// Check if the user has filled in username and password:
    	// If so; make log in button enabled
    	TextWatcher tW = new TextWatcher() {
    		public void afterTextChanged(Editable s) {}
            public void beforeTextChanged(CharSequence s, int start, int count, int after){}
            public void onTextChanged(CharSequence s, int start, int before, int count){ // Check that both fields has been filled
            	if (txtPassword.length() >=passwordLength && txtUsername.length() >=usernameLength) btnLogIn.setEnabled(true);
            	else btnLogIn.setEnabled(false);
            	if (!btnLogIn.isEnabled()) btnLogIn.setTextColor(ActLogIn.this.getResources().getColor(R.color.lblAssignmentDescriptionDisabled));
            	else btnLogIn.setTextColor(ActLogIn.this.getResources().getColor(R.color.colorBtnText));
            }
    	};
        
        txtPassword.addTextChangedListener(tW); 
        txtUsername.addTextChangedListener(tW); 
        
        // Listener for new user button
        btnNewUser.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent intent = new Intent(ActLogIn.this,ActNewUser.class);
				startActivity(intent);
				ActLogIn.this.finish();
			}
		});
        
        // Listener for log in button:
        btnLogIn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) { 
				//Trim fields:
				txtUsername.setText(txtUsername.getText().toString().trim());
				txtPassword.setText(txtPassword.getText().toString().trim());
				//Try to log in:
				if (control.isOnline()) { // The device is online:	
					String title = "Logg inn"; // Log in
					String message = "Arbeider.."; // Working.. 
					dialog = ProgressDialog.show(ActLogIn.this, title, message);
					dialog.setCancelable(false);
					control.chkDBLogInData(txtUsername.getText().toString(), txtPassword.getText().toString());
				} else {
					String message = "Ingen internett tilgang"; // Internet not available
					Toast t = Toast.makeText(ActLogIn.this, message, Toast.LENGTH_LONG);
					t.show();
				}
			}
		});
    }
    
    
    @Override
    public void onResume() {
    	super.onRestart();
    	control.setContext(ActLogIn.this);
    }
    
    public void dbWorkFinished(String result) {
    	dialog.dismiss();
    	if (result.equals("Log in: Wrong")){
    		String message = "Feil brukernavn og/eller passord"; // Wrong username and/or password
    		Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
    		t.show();	
    	}  else if (result.equals("Log in: Right")) {
    		// Open menu:
    		Intent intent = new Intent(ActLogIn.this,ActMainScreen.class);
			startActivity(intent);
			ActLogIn.this.finish();
    	}	
    }
    
    public void dbWorkAborted(String error) {
		dialog.dismiss();
		String message = "En feil skjedde\n\n"; // An error happened
		Toast t = Toast.makeText(this, message+error, Toast.LENGTH_LONG);
		t.show();
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.act_log_in, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle menu click
        switch (item.getItemId()) {
        case R.id.lost_password:
        	Intent intent = new Intent(ActLogIn.this,ActLostPassword.class);
			startActivity(intent);
			ActLogIn.this.finish();
            return true;
        case R.id.act_log_in_help:
        	String url = "http://www.lillesto.net/hjelpeside/index.html";
        	Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        	startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}
